package com.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lxk on 2020/1/18.
 */
public class Solution13 {

    private static final Map<Character, Character> helpMap = new HashMap<>();

    private static final Map<Character, Integer> char2Num = new HashMap<>();

    static {
        char2Num.put('I', 1);
        char2Num.put('V', 5);
        char2Num.put('X', 10);
        char2Num.put('L', 50);
        char2Num.put('C', 100);
        char2Num.put('D', 500);
        char2Num.put('M', 1000);

        helpMap.put('V', 'I');
        helpMap.put('X', 'I');
        helpMap.put('L', 'X');
        helpMap.put('C', 'X');
        helpMap.put('D', 'C');
        helpMap.put('M', 'C');
    }

    public int romanToInt(String s) {
        int num = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            Integer curNum = null;
            //需要减法
            if (helpMap.get(s.charAt(i)) != null) {
                char next = helpMap.get(s.charAt(i));
                if (i - 1 >= 0 && s.charAt(i - 1) == next) {
                    curNum = char2Num.get(s.charAt(i)) - char2Num.get(s.charAt(i - 1));
                    i--;
                } else {
                    curNum = char2Num.get(s.charAt(i));
                }
            } else {
                curNum = char2Num.get(s.charAt(i));
            }
            num += curNum;
        }
        return num;
    }

}
